package handler

import (
	"booking/locales"
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	"reflect"
	"strings"
)

const (
	ApiLimiterCacheKeyPre = "api:limiter:cachePre:"
)

const (
	HTTP_STATUS_OK      = 200
	HTTP_STATUS_500     = 500
	CODE_SILENT         = 0
	CODE_WARN_MESSAGE   = 1
	CODE_ERROR_MESSAGE  = 2
	CODE_NOTIFICATION   = 3
	CODE_NOT_LOGIN      = 4
	CODE_NO_PERMISSION  = 5
	CODE_TIME_OUT       = 6
	CODE_REPEAT_REQUEST = 7
	CODE_NOT_EXIST      = 8
	CODE_REDIRECT       = 9
)

var (
	CodeMsg = map[int]string{
		CODE_SILENT:         "操作成功",
		CODE_ERROR_MESSAGE:  "操作失败",
		CODE_NOT_LOGIN:      "未登录",
		CODE_REPEAT_REQUEST: "请勿重复操作",
		CODE_NO_PERMISSION:  "暂无权限访问",
		CODE_TIME_OUT:       "请求超时",
		CODE_NOT_EXIST:      "信息不存在",
	}
)

type Data struct {
	TotalCount int64 `json:"total_count"`
	TotalPage  int   `json:"total_page"`
	PageIndex  int   `json:"page_index"`
	PageSize   int   `json:"page_size"`
	PageCount  int   `json:"page_count"`
	List       any   `json:"list"`
}

func (d *Data) Format() {
	if reflect.TypeOf(d.List).Kind() != reflect.Slice {
		d.PageCount = 0
	} else {
		ins := reflect.ValueOf(d.List)
		d.PageCount = ins.Len()
	}
	if d.TotalCount == 0 {
		d.TotalPage = 0
	} else {
		d.TotalPage = int(d.TotalCount) / d.PageSize
	}

	if int(d.TotalCount)%d.PageSize != 0 {
		d.TotalPage++
	}
}

func Response(c *gin.Context, data interface{}, code int, msg string) {
	response := map[string]interface{}{
		"data":         data,
		"errorCode":    code,
		"errorMessage": msg,
	}
	c.JSON(http.StatusOK, response)
	return
}

func Error(msg string, c *gin.Context) {
	msg = strings.TrimSpace(msg)
	if msg == "" {
		msg = CodeMsg[CODE_ERROR_MESSAGE]
	}
	c.JSON(HTTP_STATUS_OK, map[string]any{
		"success":      false,
		"errorCode":    CODE_ERROR_MESSAGE,
		"errorMessage": msg,
		"data":         []any{},
	})
	return
}

func Success(response any, c *gin.Context) {
	if response == nil {
		response = []any{}
	}
	c.JSON(HTTP_STATUS_OK, map[string]any{
		"success":      true,
		"errorCode":    CODE_SILENT,
		"errorMessage": CodeMsg[CODE_SILENT],
		"data":         response,
	})
	return
}

func SuccessMsg(response any, message string, c *gin.Context) {
	language := c.GetString("lang")
	if response == nil {
		response = []any{}
	}
	if message == "" {
		message = locales.T(language, fmt.Sprintf("code_msg.%d", CODE_SILENT))
	}
	c.JSON(HTTP_STATUS_OK, map[string]any{
		"success":      true,
		"errorCode":    CODE_SILENT,
		"errorMessage": message,
		"data":         response,
	})
	return
}

func ErrorCodeMsg(code int, msg string, c *gin.Context) {
	if code <= 0 {
		code = CODE_ERROR_MESSAGE
	}
	language := c.GetString("lang")
	msg = strings.TrimSpace(msg)
	if msg == "" {
		msg = locales.T(language, fmt.Sprintf("code_msg.%d", code))
	}
	c.JSON(HTTP_STATUS_OK, map[string]any{
		"success":      false,
		"errorCode":    code,
		"errorMessage": msg,
		"data":         []any{},
	})
	return
}
